<template>
  <div class="excel-preview-container">
    <div class="sheet-tabs" v-if="sheetNames.length > 1">
      <button
        v-for="(sheet, index) in sheetNames"
        :key="index"
        @click="selectSheet(index)"
        :class="{ active: currentSheetIndex === index }"
        class="sheet-tab"
      >
        {{ sheet }}
      </button>
    </div>
    <div class="excel-content" ref="excelContainer"></div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  name: 'ExcelPreview',
  props: {
    fileData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      workbook: null,
      sheetNames: [],
      currentSheetIndex: 0
    };
  },
  mounted() {
    this.parseExcel();
  },
  methods: {
    parseExcel() {
      try {
        const data = new Uint8Array(this.fileData);
        this.workbook = XLSX.read(data, { type: 'array' });
        this.sheetNames = this.workbook.SheetNames;

        if (this.sheetNames.length > 0) {
          this.renderSheet(0);
        }
      } catch (error) {
        console.error('Excel 文件解析失败:', error);
        this.$emit('error', 'Excel 文件解析失败');
      }
    },

    renderSheet(index) {
      if (!this.workbook || !this.sheetNames[index]) return;

      try {
        this.currentSheetIndex = index;
        const sheetName = this.sheetNames[index];
        const sheet = this.workbook.Sheets[sheetName];

        // 转换为 HTML 表格
        const htmlTable = XLSX.utils.sheet_to_html(sheet, { id: 'excel-table' });
        this.$refs.excelContainer.innerHTML = htmlTable;

        // 添加样式到表格
        const table = this.$refs.excelContainer.querySelector('table');
        if (table) {
          table.classList.add('styled-table');
        }
      } catch (error) {
        console.error('Excel 表格渲染失败:', error);
        this.$emit('error', 'Excel 表格渲染失败');
      }
    },

    selectSheet(index) {
      this.renderSheet(index);
    }
  }
};
</script>

<style scoped>
.excel-preview-container {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.sheet-tabs {
  display: flex;
  overflow-x: auto;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.sheet-tab {
  padding: 8px 16px;
  border: none;
  background: none;
  cursor: pointer;
  white-space: nowrap;
  font-size: 14px;
}

.sheet-tab.active {
  background-color: white;
  border-bottom: 2px solid #2196F3;
  font-weight: bold;
}

.excel-content {
  padding: 10px;
  overflow: auto;
  max-height: 600px;
}

:deep(.styled-table) {
  border-collapse: collapse;
  width: 100%;
  font-size: 14px;
}

:deep(.styled-table th),
:deep(.styled-table td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

:deep(.styled-table tr:nth-child(even)) {
  background-color: #f2f2f2;
}

:deep(.styled-table th) {
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #f5f5f5;
  color: #333;
  position: sticky;
  top: 0;
}
</style>